//
//  NXSegementContentView.m
//  NXScrollPageView
//
//  Created by N-X on 2018/3/24.
//  Copyright © 2018年 MRNAN. All rights reserved.
//

#import "NXSegementContentView.h"
#import "NXScrollSegementView.h"
#import "UIViewController+NXSegementController.h"


@interface NXSegementContentView()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
@property (nonatomic ,strong)UICollectionView * collectionView;
@property (nonatomic ,strong)UICollectionViewFlowLayout * layout;
@property (nonatomic ,weak)NXScrollSegementView * segementView;
@property (nonatomic ,weak)UIViewController * parentViewController;
@property(nonatomic,assign)CGFloat beginTranslate;
@property(nonatomic,assign)CGFloat toIndex;
@property(nonatomic,assign)CGFloat fromIndex;
@property(nonatomic,assign)NSInteger itemCount;
@property (nonatomic ,strong)UIViewController * currentViewController;
@property (nonatomic ,strong)NSMutableDictionary<NSString *,UIViewController *> * childVcsDict;
@end

@implementation NXSegementContentView

- (instancetype)initWithFrame:(CGRect)frame segementView:(NXScrollSegementView *)segementView segementStyle:(NXSegementTitleStyle *)segementStyle parantViewController:(UIViewController *)parentViewController delegate:(id<NXSegementPageDelegate>)delegate
{
    if (self = [super initWithFrame:frame]) {
        _segementView = segementView;
        _parentViewController = parentViewController;
        _delegate = delegate;
        if ([_delegate respondsToSelector:@selector(numberOfChildrenViewControllers)]) {
            _itemCount = [_delegate numberOfChildrenViewControllers];
        }else
        {
            NSAssert(NO, @"必须实现的代理方法 : numberOfChildrenViewControllers");
        }
        [self addSubview:self.collectionView];
    }
    return self;
}

#pragma mark - lazy method

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:self.layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = YES;
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collectionCell"];
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)layout
{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc]init];
        _layout.itemSize = CGSizeMake(self.bounds.size.width, self.bounds.size.height);
        _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _layout.minimumLineSpacing = 0;
        _layout.minimumInteritemSpacing = 0;
    }
    return _layout;
}

- (NSMutableDictionary<NSString *,UIViewController *> *)childVcsDict
{
    if (!_childVcsDict) {
        _childVcsDict = [NSMutableDictionary dictionary];
    }
    return _childVcsDict;
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _itemCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255 / 255.0 green:arc4random()%255 / 255.0 blue:arc4random()%255 / 255.0 alpha:1];
    
    // 防止cell复用导致UI问题，先清空一下
    for (UIView * subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    
    _currentViewController = [self.childVcsDict valueForKey:[NSString stringWithFormat:@"%ld",indexPath.item]];
    if ([_delegate respondsToSelector:@selector(segementController:index:)]) {
        
        if (!_currentViewController) {
            _currentViewController = [_delegate segementController:nil index:indexPath.item];
            _currentViewController.nx_currentIndex  = indexPath.item;
            [self.childVcsDict setValue:_currentViewController forKey:[NSString stringWithFormat:@"%ld",indexPath.item]];
        }else
        {
            [_delegate segementController:_currentViewController index:indexPath.item];
        }
    }else
    {
        NSAssert(NO, @"必须实现的代理方法 : segementController:index:");
    }
    
    [cell.contentView addSubview:_currentViewController.view];
    _currentViewController.view.frame = cell.contentView.bounds;
    [_currentViewController didMoveToParentViewController:self.parentViewController];
    return cell;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.beginTranslate = scrollView.contentOffset.x;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView.contentOffset.x <= 0 || scrollView.contentOffset.x >= scrollView.contentSize.width - scrollView.bounds.size.width) {
        return;
    }
    
    CGFloat tempProgress = scrollView.contentOffset.x / self.bounds.size.width;
    NSInteger tempIndex = tempProgress;
    CGFloat  progress = tempProgress - floorf(tempProgress);
    CGFloat delta = scrollView.contentOffset.x - self.beginTranslate ;
    NSInteger fromIndex = 0;
    NSInteger toIndex = 0;
    
    if (delta > 0) { // 左滑
        if (progress == 0) {
            return;
        }
        fromIndex = tempIndex;
        toIndex = tempIndex + 1;
        
        NSLog(@"左滑==");
        
    }else if(delta < 0) // 右滑
    {
        progress = 1 - progress;
        toIndex = tempIndex ;
        fromIndex = tempIndex + 1;
        NSLog(@"右滑==");
    }else
    {
        return;
    }
//    NSLog(@"contentOffSet:%f \n",scrollView.contentOffset.x);
//    NSLog(@"width        :%f \n",self.bounds.size.width);
//    NSLog(@"tempProgress :%f  \n",tempProgress);
//    NSLog(@"tempIndex    :%ld \n",tempIndex);
//    NSLog(@"toIndex      :%ld \n",toIndex);
//    NSLog(@"fromIndex    :%ld \n",fromIndex);
//    NSLog(@"================================================");
    [self.segementView adjustUIWithProgress:progress fromImdex:fromIndex toIndex:toIndex];
}

/** 滚动减速完成时再更新title的位置 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger currentIndex = (scrollView.contentOffset.x / self.bounds.size.width);
    // 调整title
    [self.segementView adjustTitleLabelWithIndex:currentIndex];
}


#pragma mrak - private method

#pragma mark - public method
- (void)setContentOffSet:(CGPoint)contentOffSet animated:(BOOL)animated
{
    [self.collectionView setContentOffset:contentOffSet animated:animated];
}
@end
